"""
Case Type   : 资源池化-多节点写入
Case Name   : 备机执行定义模式的DDL语句
Create At   : 2024/04/30
Owner       : zhengxue
Description :
    1.修改enable_remote_execute参数值为on
    2.备机执行定义模式的DDL语句
    3.备机查看日志打印
    4.恢复参数
Expect      :
    1.修改成功
    2.执行成功
    3.日志记录建立连接、转发给主机、接受执行结果等libpqsw信息
    4.恢复参数成功
Pre-operation:
    1.在conf/macro.yml中配置PG_LOG_PATH为数据库pg_log目录,对应用例中的macro.PG_LOG_PATH
History     :
    1、2024-04-30 创建
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')


class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.schema_name1 = 'schema_write_transfer_case0008_1'
        self.schema_name2 = 'schema_write_transfer_case0008_2'
        self.new_log_dir = os.path.join(macro.PG_LOG_PATH,
                                        'pg_log_write_transfer_case0008')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, f'执行失败:{step1}')
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', f'执行失败:{step1}')
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.new_log_dir}'", single=True)
        self.assertTrue(result, f'执行失败:{step1}')

        step2 = "-----step2:备机执行定义模式的DDL语句;expect:执行成功-----"
        self.logger.info(step2)
        sql_cmd = f'''drop schema if exists {self.schema_name1},
            {self.schema_name2};
            create schema {self.schema_name1};
            alter schema {self.schema_name1} rename to {self.schema_name2};
            drop schema {self.schema_name2};'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step2}')
        self.assertIn(self.constant.ALTER_SCHEMA_SUCCESS_MSG,
                      sql_msg, f'执行失败:{step2}')
        self.assertEquals(2, sql_msg.count(
            self.constant.DROP_SCHEMA_SUCCESS_MSG), f'执行失败:{step2}')
        time.sleep(3)

        step3 = "-----step3:备机查看日志打印;expect:日志记录建立连接、" \
                "转发给主机、接受执行结果等libpqsw信息-----"
        self.logger.info(step3)
        shell_cmd = f"ls -t {self.new_log_dir}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_dir, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn('we find new transfer request',
                      shell_msg, f'执行失败:{step3}')
        self.assertIn('Connecting to remote server',
                      shell_msg, f'执行失败:{step3}')
        self.assertIn(f'LOG:  libpqsw', shell_msg, f'执行失败:{step3}')

    def tearDown(self):
        step4 = "-----step4:恢复参数;expect:恢复参数成功-----"
        self.logger.info(step4)
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)        
        result1 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        status = Primary_SH.check_cluster_core_status(status, wait_times=600)
        self.logger.info(status)
        restart_res = self.standby_sh.restart_db_cluster()
        recovery = Primary_SH.exec_cm_ctl(mode='switchover', param='-a')
        self.logger.info(recovery)
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"{self.log_directory}='{self.log_dir_default}'", single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        self.logger.info("-----断言teardown-----")
        self.assertTrue(result1, f'执行失败:{step4}')
        self.assertTrue(restart_res, f'执行失败:{step4}')
        self.assertIn(self.constant.cm_switchover_success_msg, recovery,
                      '执行失败' + step4)
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step4}')
        self.assertTrue(result2, f'执行失败:{step4}')
        self.assertTrue(result3, f'执行失败:{step4}')
        self.assertEquals(show_log_statement, self.log_statement_default,
                          f'执行失败:{step4}')
        self.assertEquals(show_log_directory, self.log_dir_default,
                          f'执行失败:{step4}')
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
